package com.yanxu.proxy.proxy_dynamic;


import com.yanxu.proxy.base.Order;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author 折戟沉沙铁未销
 * @version V1.0
 * @date 2025/4/15-2025
 * @Description: 这里用一句话描述这个类的作用
 */
public class OrderServiceDynamicProxy implements InvocationHandler {

    private Object target;

    public OrderServiceDynamicProxy(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //前置增强
        beforeMethod(args[0]);

        Object result = method.invoke(target, args);

        //后置增强
        afterMethod();
        return result;
    }

    public Object getProxy() {
        Class<?> clazz = target.getClass();
        Object o = Proxy.newProxyInstance(
                clazz.getClassLoader(),
                clazz.getInterfaces(),
                this);
        return o;
    }

    private Integer beforeMethod(Object obj){
        System.out.println("before method");
        int num=0;
        if(obj instanceof Order){
            Order order = (Order) obj;
            Integer userId = order.getUserId();
            num = userId % 2;
            System.out.println("动态代理分配到db【"+num+"】 处理数据!");
        }
        return num;
    }

    private void afterMethod(){
        System.out.println("after method");
    }
}